const express = require("express");
const { createServer } = require("http");
const log = require('../frontend/utils/log')
const app = express();
const httpServer = createServer(app);
const io = require("socket.io")(httpServer, {  
    cors: {    
        origin: "http://localhost:3000",    
        methods: ["GET", "POST"]  
    }
});
const utf8 = require('utf8');
const SSHClient = require('ssh2').Client;

// 主进程中
const ipcMain = require('electron').ipcMain;
ipcMain.on('async-msg', function(event, machineConfig, socket) {
  log.debug('createNewServer start=================')
  console.log('createNewServer start=================')
  createNewServer(machineConfig, socket);
  event.sender.send('async-reply', 'pong');
});

function createNewServer(machineConfig, socket) {
    //console.log("createNewServer====================");
    var ssh = new SSHClient();
    let {msgId, ip, port, username, password} = machineConfig;
    if(port==null || port=="" || port==undefined) {
        port = 22;
    }
    ssh.on('ready', function () {
        socket.emit(msgId, '\r\n***' + ip + ' SSH CONNECTION ESTABLISHED ***\r\n');
        ssh.shell(function(err, stream) {
            if(err) {
                return socket.emit(msgId, '\r\n*** SSH SHELL ERROR: ' + err.message + ' ***\r\n');
            }
            socket.on(msgId, function (data) {
                stream.write(data);
            });
            stream.on('data', function (d) {
                socket.emit(msgId, utf8.decode(d.toString('binary')));
            }).on('close', function () {
                ssh.end();
            });
        })
    }).on('close', function () {
        socket.emit(msgId, '\r\n*** SSH CONNECTION CLOSED ***\r\n');
    }).on('error', function (err) {
        console.log(err);
        socket.emit(msgId, '\r\n*** SSH CONNECTION ERROR: ' + err.message + ' ***\r\n');
    }).connect({
        host: ip,
        port: port,
        username: username,
        password: password
    });
}

/*io.on("connection", (socket) => {  
    socket.on('createNewServer', function(machineConfig) {//新建一个ssh连接
        console.log("createNewServer")
        createNewServer(machineConfig, socket);
    })
 
    socket.on('disconnect', function(){
        console.log('user disconnected');
    });
});
httpServer.listen(8000);*/